//
//  OAuthViewController.swift
//  sinaWB
//
//  Created by 杨运旺 on 15/11/9.
//  Copyright © 2015年 杨运旺. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    
    private lazy var webView = UIWebView()
    
    // MARK: - 监听方法
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil);
    }
    // MARK: - 自动填充账号密码
    @objc private func autoFill(){
        let js = "document.getElementById('userId').value = '15101634386';" +
        "document.getElementById('passwd').value = 'Yang!419726';"
        // 让 webView 执行 js
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    // MARK: - 设置界面
    override func loadView() {
        view = webView
        
        // 设置代理
        webView.delegate = self
        // 设置导航栏
        
        title = "登录新浪微博"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoFill")
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 加载页面
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedTools.oauthURL))

    }

}
// MARK: - UIWebViewDelegate
extension OAuthViewController:UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 目标：如果是百度，就不加载
        // 1. 判断访问的主机是否是 www.baidu.com
        guard let url  = request.URL where url.host == "www.baidu.com" else{
            return true
        }
        
        // 2. 从百度地址的 url 中提取 `code=` 是否存在
        guard let query = url.query where query.hasPrefix("code=") else{
            print("取消授权")
            self.close()
            return false
        }
        
        // 3. 从 query 字符串中提取 `code=` 后面的授权码
        
        let code = query.substringFromIndex("code=".endIndex);
        print(query)
        print("授权码是" + code)
        
        // 4.加载ToKen
        UserAccountViewModel.sharedUserAccount.loadAccessToken(code) { (isSuccessed) -> () in
            if isSuccessed{
                print("成功了")
                // dismissViewControllerAnimated 方法不会立即将控制器销毁
                self.dismissViewControllerAnimated(false){
                    
                    // 停止指示器
                    SVProgressHUD.dismiss()
                    
                    // 通知中心是同步的 - 一旦发送通知，会先执行监听方法，直接结束后，才执行后续代码
//                NSNotificationCenter.defaultCenter().postNotificationName
//                    (WBSwitchRootViewControllerNotification, object: "welcome")
//                }
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNotification, object: "welcome")
            }
            }else{
                print("失败了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                delay(0.5) {self.close()}
            }
        }
        
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
}



